<template>
    <div class="point-form">
      <!-- 加载中状态 -->
      <div v-if="loading" class="loading">
        <van-loading type="spinner" color="#1989fa" size="24px">加载中...</van-loading>
      </div>
  
      <!-- 主体内容 -->
      <template v-else>
        <!-- 点位信息 -->
        <div class="point-info">
          <div class="point-name">{{ formData.name }}</div>
          <div class="point-path">{{ formData.groupPath }}</div>
        </div>
  
        <!-- 表单列表 -->
        <div class="forms-container">
          <div v-for="form in formData.forms" :key="form.id" class="form-section">
            <!-- 表单头部 -->
            <div class="form-header">
              <h3>{{ form.name }}</h3>
            </div>
  
            <!-- 表单项列表 -->
            <div class="form-items">
              <!-- 检查状态类型表单项 -->
              <div v-for="item in getItemsByType(form.items, 'CHECK_STATUS')"
                   :key="item.id"
                   class="form-item">
                <div class="item-label">{{ item.name }}</div>
                <van-radio-group
                    v-model="formValues[form.id][item.id]"
                    direction="horizontal"
                    @change="(val) => handleCheckStatusChange(form.id, val)"
                >
                  <van-radio name="NORMAL">正常</van-radio>
                  <van-radio name="ABNORMAL">异常</van-radio>
                </van-radio-group>
              </div>
  
              <!-- 文本类型表单项 -->
              <div v-for="item in getItemsByType(form.items, 'TEXT')"
                   :key="item.id"
                   class="form-item">
                <div class="item-label">{{ item.name }}</div>
                <van-field
                    v-model="formValues[form.id][item.id]"
                    type="textarea"
                    rows="2"
                    placeholder="请输入描述"
                    class="text-field"
                />
              </div>
  
              <!-- 图片类型表单项 -->
              <div v-for="item in getItemsByType(form.items, 'IMAGE_LIST')"
                   :key="item.id"
                   class="form-item">
                <div class="item-label">{{ item.name }}</div>
                <div class="image-uploader">
                  <van-uploader
                      v-model="formValues[form.id][item.id]"
                      :before-read="beforeRead"
                      :after-read="afterRead"
                      multiple
                      capture="camera"
                      accept="image/*"
                      :max-count="9"
                      :max-size="800 * 1024"
                      @oversize="onOversize"
                  >
                    <template #preview-cover="{ file }">
                      <div class="preview-cover">
                        <van-icon
                            name="clear"
                            class="preview-delete"
                            @click.stop="() => handleImageDelete(file)"
                        />
                      </div>
                    </template>
                  </van-uploader>
                </div>
              </div>
  
              <!-- 总体检查结果 -->
              <div class="form-item check-result-section">
                <div class="item-label">总体检查结果</div>
                <van-radio-group
                    v-model="formValues[form.id].checkResult"
                    direction="horizontal"
                >
                  <van-radio name="NORMAL">正常</van-radio>
                  <van-radio name="ABNORMAL">异常</van-radio>
                </van-radio-group>
              </div>
            </div>
          </div>
        </div>
  
        <!-- 提交按钮 -->
        <div class="submit-button">
          <van-button type="primary" block round :loading="submitting" @click="handleSubmit">
            提交
          </van-button>
        </div>
      </template>
  
      <!-- 成功页面弹窗 -->
      <van-dialog
          v-model:show="showSuccess"
          title="提交成功"
          showCancelButton
          confirmButtonText="继续扫码"
          cancelButtonText="返回首页"
          @confirm="handleScan"
          @cancel="handleCancel"
      >
        <div class="success-content">
          <van-icon name="success" class="success-icon" />
          <p>表单已提交成功！</p>
        </div>
      </van-dialog>
    </div>
  </template>
  
  <script setup>
  import { onMounted, ref, watch, inject } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import Compressor from 'compressorjs'
  import { pointsForm, filesUpload, submitRecord } from "@/api/common"
  import { Uploader as VanUploader } from "vant"
  import * as dd from 'dingtalk-jsapi'
  
  const route = useRoute()
  const toast = inject("toast")
  const router = useRouter()
  
  // 状态管理
  const loading = ref(true)
  const submitting = ref(false)
  const showSuccess = ref(false)
  const formData = ref({ forms: [] })
  const formValues = ref({})
  
  // 获取表单数据
  
  // 工具方法：按类型筛选表单项
  const getItemsByType = (items, type) => {
    return items.filter(item => item.itemType === type)
  }
  
  // 处理选择状态变更
  const handleCheckStatusChange = (formId) => {
    const formValue = formValues.value[formId]
  
    // 如果任何一个检查项为异常，自动设置总体检查结果为异常
    const hasAbnormal = Object.entries(formValue)
        .some(([key, val]) =>
            key !== 'checkResult' &&
            key !== 'abnormalDesc' &&
            val === 'ABNORMAL'
        )
  
    if (hasAbnormal) {
      formValue.checkResult = 'ABNORMAL'
    }
  }
  
  // 图片上传相关处理
  const beforeRead = (file) => {
    return new Promise((resolve) => {
      new Compressor(file, {
        quality: 0.7,
        maxWidth: 1080,
        maxHeight: 1080,
        success(result) {
          resolve(result)
        },
        error(err) {
          toast.msg(err.message)
          resolve(false)
        }
      })
    })
  }
  
  const onOversize = () => {
    toast.msg('图片大小不能超过 800KB')
  }
  
  // 处理图片删除
  const handleImageDelete = (file) => {
    formData.value.forms.forEach(form => {
      const images = formValues.value[form.id]
      Object.keys(images).forEach(key => {
        if (Array.isArray(images[key])) {
          const index = images[key].findIndex(item => item === file)
          if (index > -1) {
            images[key].splice(index, 1)
          }
        }
      })
    })
  }
  
  // 处理表单提交
  const handleSubmit = async () => {
    try {
      // 检查是否有照片正在上传
      if (isUploading()) {
        // 创建动态更新的提示
        const toast = showLoadingToast({
          duration: 0,
          forbidClick: true,
          message: '正在等待照片上传完成...'
        });
  
        // 轮询检查上传状态
        const checkUploadStatus = () => {
          if (!isUploading()) {
            // 照片上传完成，关闭提示并继续提交
            toast.close();
            submitForm();
          } else {
            // 继续等待
            setTimeout(checkUploadStatus, 500);
          }
        };
  
        // 开始检查
        checkUploadStatus();
        return;
      }
  
      // 没有正在上传的照片，直接提交
      await submitForm();
    } catch (error) {
      toast.msg(error.message)
    }
  };
  
  const isUploading = () => {
    let uploading = false;
  
    // 遍历所有表单中的图片
    formData.value.forms.forEach(form => {
      const images = formValues.value[form.id];
      Object.keys(images).forEach(key => {
        if (Array.isArray(images[key])) {
          uploading = uploading || images[key].some(img => img.status === 'uploading');
        }
      });
    });
  
    return uploading;
  };

  const handleScan = async () => {
    try {
      if(!isInDingTalk()) {
        toast.error("请用钉钉扫码")
        return
      }
      let qrResult
      qrResult = await new Promise((resolve, reject) => {
        dd.scan({
          type: 'qr',
          success: resolve,
          fail: (err) => {
            reject(new Error(err.errorMessage || '扫码失败'))
          }
        })
      })
      const queryString = qrResult.text.split('#')[1];
      router.replace(queryString)

    } catch (error) {
      toast.msg(error.message || '调用扫码失败')
    }
  }

  const handleCancel = () => {
    router.replace("/dayHome")
  }

  function isInDingTalk() {
    const userAgent = navigator.userAgent.toLowerCase();
    return /dingtalk/i.test(userAgent); // 不区分大小写匹配 "dingtalk"
  }
  
  const resetForm = () => {
    formValues.value = {}
    formData.value = { forms: [] }
  }
  
  function fetchFormData(qrCode) {
    loading.value = true
    pointsForm(qrCode).then(res => {
      formData.value = res
      loading.value = false
      // 初始化表单值
      formData.value.forms.forEach(form => {
        formValues.value = {
          ...formValues.value,
          [form.id]: {}
        }

        form.items.forEach(item => {
          if (item.itemType === 'CHECK_STATUS') {
            formValues.value[form.id][item.id] = 'NORMAL'
          } else if (item.itemType === 'IMAGE_LIST') {
            formValues.value[form.id][item.id] = []
          } else {
            formValues.value[form.id][item.id] = ''
          }
        })

        // 初始化总体检查结果
        formValues.value[form.id].checkResult = 'NORMAL'
      })
    }, err => {
      toast.msg(err.message)
      loading.value = false
    })
  }

  function afterRead(file) {
    const formData = new FormData()
    formData.append('file', file.file)
    filesUpload(formData, 'RECORD_PHOTO').then(res => {
      file.url = `http://10.10.11.45:11000/uploads${res}`;
      file.path = res
      file.status = 'done';
    }, err => {
      toast.msg(err.message)
      file.status = 'failed';
    })
  }

  const submitForm = async () => {
    submitting.value = true;

    try {
      // 构建提交数据
      const submitData = formData.value.forms.map(form => ({
        formId: form.id,
        pointId: formData.value.id,
        checkResult: formValues.value[form.id].checkResult,
        itemRecords: form.items.map(item => ({
          formItemId: item.id,
          values: item.itemType === 'IMAGE_LIST'
              ? formValues.value[form.id][item.id].map(img => img.path)
              : [formValues.value[form.id][item.id]]
        }))
      }));

      // 提交每个表单
      for (const data of submitData) {
        await submitRecord(data);
      }

      showSuccess.value = true;
    } finally {
      submitting.value = false;
    }
  };

  // 监听路由参数变化
  watch(
      () => route.params.qrCode,
      (newQrCode) => {
        if (newQrCode) {
          resetForm()
          fetchFormData(newQrCode)
        }
      }
  )
  
  // 页面加载
  onMounted(() => {
    const qrCode = route.params.qrCode
    if (qrCode) {
      fetchFormData(qrCode)
    }
  })
  </script>
  
  <style scoped>
  .point-form {
    min-height: 100vh;
    background-color: #f7f8fa;
    padding-bottom: 80px;
  }
  
  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  
  .point-info {
    background: #fff;
    padding: 16px;
    margin-bottom: 12px;
  }
  
  .point-name {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 8px;
  }
  
  .point-path {
    font-size: 14px;
    color: #666;
  }
  
  .forms-container {
    padding: 12px;
  }
  
  .form-section {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 12px;
    padding: 16px;
  }
  
  .form-header {
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
  }
  
  .form-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }
  
  .form-item {
    margin-bottom: 20px;
    background: #fff;
    padding: 12px;
    border-radius: 4px;
  }
  
  .item-label {
    margin-bottom: 12px;
    font-size: 14px;
    color: #323233;
    font-weight: 500;
  }
  
  .text-field {
    background: #f8f8f8;
    border-radius: 4px;
  }
  
  :deep(.van-radio-group) {
    display: flex;
    gap: 24px;
  }
  
  :deep(.van-radio) {
    margin-right: 0;
  }
  
  .image-uploader {
    margin-top: 12px;
  }
  
  :deep(.van-uploader__upload) {
    background-color: #f7f8fa;
  }
  
  .preview-cover {
    position: relative;
    width: 100%;
    height: 100%;
  }
  
  .preview-delete {
    position: absolute;
    top: 4px;
    right: 4px;
    padding: 4px;
    color: #fff;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    font-size: 14px;
  }
  
  .submit-button {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background: #fff;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
  }
  
  :deep(.van-button--primary) {
    height: 44px;
    font-size: 16px;
  }
  
  .success-content {
    padding: 24px;
    text-align: center;
  }
  
  .success-icon {
    font-size: 48px;
    color: #07c160;
    margin-bottom: 16px;
  }
  
  .check-result-section {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #eee;
  }
  
  :deep(.van-radio-group) {
    margin: 8px 0;
  }
  
  :deep(.van-field__control) {
    background-color: #f8f8f8;
    border-radius: 4px;
    padding: 8px;
  }
  </style>